package parser

import (
	"log"
	"regexp"
	"strconv"
	"strings"

	"aqielife.cn/spider/singleSpider/zhenai/model"
	"aqielife.cn/spider/singleSpider/zhenaiDistributed/engine"
)

const profileInfoReg = `<div[^>^<]*class="des f-cl"[^>]*>([^<]+)</div>`

var idUrlReg = regexp.MustCompile(`https://album.zhenai.com/u/([\d]+)`)

func ProfileParser(content []byte,
	url string,
	name string) engine.ParseResult {
	log.Printf("%v", "User info")

	var profile model.Profile

	//匹配profileNameReg
	//nameReg := regexp.MustCompile(profileNameReg)
	//nameAll := nameReg.FindAllStringSubmatch(string(content), -1)
	//if nameAll != nil {
	//	for _,m := range nameAll {
	//		profile.Name = m[1]
	//	}
	//}
	profile.Name = name

	//匹配profileNameReg
	infoReg := regexp.MustCompile(profileInfoReg)
	infoAll := infoReg.FindAllStringSubmatch(string(content), -1)
	if infoAll != nil {
		for _, m := range infoAll {
			strs := strings.Split(m[1], "|")
			profile.City = strings.TrimSpace(strs[0])
			profile.Age, _ = strconv.Atoi(strings.TrimSpace(strs[1]))
			profile.Education = strings.TrimSpace(strs[2])
			profile.Marriage = strings.TrimSpace(strs[3])
			profile.Height, _ = strconv.Atoi(strings.TrimSpace(strs[4]))
			profile.Income = strings.TrimSpace(strs[5])
		}
	}
	//把profile的info信息放入到parseResult
	var parseResult engine.ParseResult

	parseResult.Items = []engine.Item{{
		Id:      extractString([]byte(url), idUrlReg),
		Type:    "zhenai",
		Url:     url,
		Payload: profile,
	}}

	return parseResult
}

func extractString2(
	content []byte, re *regexp.Regexp) string {
	match := re.FindSubmatch(content)
	if len(match) >= 2 {
		return string(match[1])
	}

	return ""
}

//func ProfileParser(
//	name string) engine.ParserFunc {
//	return func(bytes []byte, url string) engine.ParseResult {
//		return ParseProfile(bytes, url, name)
//	}
//}

type ParseProfileNew struct {
	username string
}

func (p *ParseProfileNew) Parse(contents []byte, url string) engine.ParseResult {
	return ProfileParser(contents, url, p.username)
}

func (p *ParseProfileNew) Serialize() (name string, args interface{}) {
	return "ParseProfileNew", p.username
}

func NewParseProfile(name string) *ParseProfileNew {
	return &ParseProfileNew{
		username: name,
	}
}
